<?php

session_start();
include ("util/Connection.php");

//header('Content-Type: text/html; charset=ISO-8859-15');

if (isset($_POST['metodo'])) {
    $method = $_POST['metodo'];

    $usuario = new Usuario();
    $usuario->$method();
}

class Usuario {

    public function __construct() {
        
    }

    //TODO - VERIFICAR SESSAO NAS PAGINAS DE ADMIN UTILIZANDO ESSE METODO
    static function verifySession() {
        if (!isset($_SESSION['logado']) || $_SESSION['logado'] == 0) {
            header("Location: ./login.php");
        }
    }

    function login() {
        $usuario = $_POST["usuario"];
        $senha = md5($_POST["senha"]);

        $con = Connection::getConnection();

        $stmt = $con->prepare("SELECT true FROM usuario WHERE login = ? AND senha = ?");
        $stmt->bind_param('ss', $usuario, $senha);
        $stmt->execute();

        $result = $stmt->get_result();
        $count = $result->num_rows;

        if ($count > 0) {
            $_SESSION['logado'] = 1;
            echo true;
        } else {
            echo false;
        }
        
        $con->close();
    }

    function logoff() {
        session_destroy();
    }

    function atualizarSenha() {
        $novaSenha = hash('MD5', $_POST['senha']);

        $con = Connection::getConnection();

        $stmt = $con->prepare("UPDATE usuario SET senha = ? WHERE login = 'renascer'");
        $stmt->bind_param('s', $novaSenha);
        echo $stmt->execute();
        
        $con->close();
    }

}

?>
